#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "Usage : ./prime_num_sieve.sh arg1 arg2"
    exit 1
fi

num1=$1
num2=$2

#以下部分为参数合法性判断
expr 1 + ${num1} &>/dev/null
if [[ $? -ne 0 ]] || [[ $? -ne 1 ]]; then
    echo "the first arg is not a num"
    exit 2;
fi

expr 1 + ${num2} &>/dev/null
if [[ $? -ne 0 ]] || [[ $? -ne 1 ]]; then
    echo "the first arg is not a num"
    exit 3;
fi

if [[ ${num1} -gt ${num2} ]]; then
    echo "the first arg should be smaller than the second args"
    exit 4;
fi

if [[ ${num2} -gt 1000 ]]; then
    echo "the second arg should be smaller or equal than 1000"
    exit 5
fi

if [[ ${num1} -lt 0 ]]; then
    num1=0
fi

#计算过程
nums=(`seq 0 ${num2}`)
#echo ${nums[*]}

end=`expr ${num2} / 2`
#echo ${end}

i=2

while [[ ${i} -le ${end} ]]; do
    if [[ ${nums[i]} -ne 0 ]];then
        temp=${i}
        for (( temp+=${i}; temp <= ${num2}; temp+=${i})); do
            nums[temp]=0
        done
    fi
    i=${i}+1
done

i=${num1}
sum=0
while [[ ${i} -le ${num2} ]]; do
    sum=`expr ${sum} + ${nums[i]}`
    i=${i}+1
done
echo ${sum}
echo ${nums[*]}